package com.epoch.platform.sys.serialnumber.controller;

import java.math.BigDecimal;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;

import com.epoch.base.annotation.ControllerBind;
import com.epoch.base.base.BaseController;
import com.epoch.base.util.AjaxResult;
import com.epoch.base.util.ExtStringUtils;
import com.epoch.base.util.LoggerUtil;
import com.epoch.platform.sys.serialnumber.dao.SerialNumber;
import com.epoch.platform.sys.serialnumber.service.SerialNumberService;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.ActiveRecordException;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;

@ControllerBind(controllerKey = "/sys/serialnumber")
public class SysSerialNumberController extends BaseController {

	private static final Logger LOGGER = LoggerUtil.getLogger();

	private static final String FORM_MODEL_NAME = "serialNumber";

	private SerialNumberService service = this.enhance(SerialNumberService.class);

	public void index() {
		this.render("/sys/serialnumber/sys_serialnumber_tab.html");
	}

	public void listUI() {
		this.render("/sys/serialnumber/sys_serialnumber_list.html");
	}

	public void suvUI() {
		String id = this.getPara("id");
		SerialNumber serialNumber = new SerialNumber();
		if (id != null) {
			serialNumber = SerialNumber.dao.findById(id);
		}
		this.setAttr("serialNumber", serialNumber);
		this.render("/sys/serialnumber/sys_serialnumber_edit.html");
	}

	public void findSerialNumberListAjax() {
		Page<SerialNumber> page = null;
		AjaxResult result = new AjaxResult();
		String operNote = null;
		Kv param = this.commonParams();
		try {
			SqlPara sqlPara = Db.getSqlPara("systemManage.findSerialNumberList", param);
			page = SerialNumber.dao.paginate(sqlPara, param);
			operNote = "查询流水号规则成功";
		} catch (Exception e) {
			operNote = "查询流水号规则失败";
			result.addError(operNote);
			result.setData(e);
		}
		this.renderJson(page);
	}

	public void save() {
		AjaxResult result = new AjaxResult();
		SerialNumber model = this.getModel(SerialNumber.class, FORM_MODEL_NAME);
		boolean success = false;
		try {
			success = this.service.saveSeriNum(model);
		} catch (Exception e) {
			LOGGER.error(ExtStringUtils.format("保存流水号规则失败！({0})", model), e);
			result.setData(e);
		}
		if (success) {
			result.success("保存成功。");
		} else {
			result.addError("保存失败。");
		}
	}

	public void delete() {
		AjaxResult result = new AjaxResult();
		String[] ids = this.getParaValuesToString("ids[]");
		if (ArrayUtils.isNotEmpty(ids)) {
			try {
				boolean success = this.service.delSeriNums(ids);
				if (success) {
					result.success("删除成功。");
				} else {
					result.addError("删除失败。");
				}
			} catch (ActiveRecordException e) {
				LOGGER.error(ExtStringUtils.format("删除流水号规则失败(ID:{0})", StringUtils.join(ids, ',')), e);
				result.addError("删除失败。");
				result.setData(e);
			}
		}
		String operNote = ExtStringUtils.format("删除流水号规则(ID:{0})", StringUtils.join(ids, ','));
		this.renderJson(result);
	}

	// 检查规则编码是否重复
	public void checkRuleCode() {
		String ruleCode = this.getPara(FORM_MODEL_NAME + "." + SerialNumber.RULE_CODE);
		String seriNumId = this.getPara(FORM_MODEL_NAME + "." + SerialNumber.ID);
		this.renderText(
				this.doCheckRuleCode(seriNumId == null ? null : seriNumId, ruleCode));
	}

	// 检查规则名称是否重复
	public void checkRuleName() {
		String ruleName = this.getPara(FORM_MODEL_NAME + "." + SerialNumber.RULE_NAME);
		String seriNumId = this.getPara(FORM_MODEL_NAME + "." + SerialNumber.ID);
		this.renderText(
				this.doCheckRuleName(seriNumId == null ? null : seriNumId, ruleName));
	}
	
	private String doCheckRuleCode(String seriNumId, String ruleCode) {
        String msg = "";
        String key = seriNumId == null ? null : seriNumId;
        if (this.checkExist(key, ruleCode, "rule_code")) {
            msg = "规则编码已存在";
        }
        return msg;
    }

    private String doCheckRuleName(String seriNumId, String ruleName) {
        String msg = "";
        String key = seriNumId == null ? null : seriNumId;
        if (this.checkExist(key, ruleName, "rule_name")) {
            msg = "规则名称已存在";
        }
        return msg;
    }
    
    private boolean checkExist(String key, String val, String field) {
        boolean exist = false;
        if (StringUtils.isNotEmpty(val) && StringUtils.isNotEmpty(field)) {
            SerialNumber model = SerialNumber.dao.findFirst("SELECT id FROM sys_serial_number  WHERE " + field + " = ? ", val);
            if (model != null && !model.getStr(SerialNumber.ID).equals(key)) {
                exist = true;
            }
        }
        return exist;
    }
}
